package com.service.login.controller;

import com.service.config.utils.*;
import com.service.login.bean.MailBean;
import com.service.login.dto.UserExtendDto;
import com.service.login.dto.UserLoginRecordDto;
import com.service.login.entity.CustomerServiceInfo;
import com.service.login.entity.UserInfo;
import com.service.login.entity.UserLoginRecord;
import com.service.login.service.CustomerServiceInfoService;
import com.service.login.service.UserExtendService;
import com.service.login.service.UserInfoService;
import com.service.login.service.UserLoginRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import static com.service.config.constant.Constant.*;
import static com.service.login.controller.UserInfoController.clearCache;

/**
 * 系统运维人员信息表(CustomerServiceInfo)表控制层
 *
 * @author makejava
 * @since 2021-05-08 17:36:16
 */
@RestController
@RequestMapping("customerServiceInfo")
@Api(value = "系统运维人员信息",description = "系统运维人员信息表")
public class CustomerServiceInfoController {
    /**
     * 服务对象
     */
    @Resource
    private CustomerServiceInfoService customerServiceInfoService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private UserLoginRecordService userLoginRecordService;
    @Resource
    private UserExtendService userExtendService;
    /**
     * 通过主键查询单条数据
     *
     * @param customerServiceInfo
     * @return 单条数据
     */
    @PostMapping(value = "auth",produces="application/json")
    @ApiOperation(value = "统一登录")
    @ResponseBody
    public Result customerLogin(@RequestBody CustomerServiceInfo customerServiceInfo) throws Exception {
        HashMap map = new HashMap();
        customerServiceInfo= customerServiceInfoService.queryAllByNameAndPassword(customerServiceInfo);
        String token = UserTokenManager.generateToken(customerServiceInfo.getId());
        redisUtil.set(token,4, JsonXMLUtils.obj2json(customerServiceInfo),2);
        map.put("Token",token);
        return Result.ok().setData(map);
    }
    /**
     * 客服退出登录
     *
     * @param cloudAuthToken
     * @return 单条数据
     */
    @PostMapping(value = "loginOut",produces="application/json")
    @ApiOperation(value = "客服退出登录")
    @ResponseBody
    public Result customerLogin(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            if (redisUtil.exist(cloudAuthToken)) {
                redisUtil.delete(cloudAuthToken);
                return Result.ok();
            }
        }
        return Result.ok();
    }
    /**
     * 客服退出登录
     *
     * @param cloudAuthToken
     * @return 单条数据
     */
    @GetMapping(value = "customerLoginUserRecord",produces="application/json")
    @ApiOperation(value = "用户登录记录")
    @ResponseBody
    public Result customerLoginUserRecord(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken,
                                          @RequestParam("serviceId") String serviceId,
                                          @RequestParam("userId") String userId) throws Exception {
        if (cloudAuthToken != null && !cloudAuthToken.equals("")) {
            UserLoginRecord userLoginRecord = new UserLoginRecord();
            userLoginRecord.setUserId(userId);
            long countOnlineTime = 0;
            List<UserLoginRecord> userLoginRecordList = new ArrayList<>();
            if (serviceId.equals("1")) { // 大屏服务
                userLoginRecordList = userLoginRecordService.queryAll(userLoginRecord);
            }
            if (serviceId.equals("2")){// msp服务
                userLoginRecordList = userLoginRecordService.queryAllMsp(userLoginRecord);
            }
            if (userLoginRecordList != null) {
                for (UserLoginRecord userLoginRecord1 : userLoginRecordList ) {
                    countOnlineTime += userLoginRecord1.getOnlineTime();
                }
            }
            UserLoginRecordDto userLoginRecordDto = new UserLoginRecordDto();
            userLoginRecordDto.setUserId(userId);
            userLoginRecordDto.setOnlineTime(countOnlineTime);
            userLoginRecordDto.setUserLoginRecordList(userLoginRecordList);
            return Result.ok().setData(userLoginRecordDto);
        }
        return Result.ok();
    }
    /**
     * 通过主键查询单条数据
     * 销号 或者封号
     * @return 单条数据
     */
    @GetMapping(value = "isLogout",produces="application/json")
    @ApiOperation(value = "销号或者封号")
    @ResponseBody
    public Result customerLogin(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken,
                                @RequestParam("serviceId") String serviceId,
                                @RequestParam("userId") String userId,
                                @RequestParam("isLogout") Boolean isLogout) throws Exception {
        if (redisUtil.exist(cloudAuthToken)) { // 销号 或者封号
            UserInfo userInfo = new UserInfo();
            userInfo.setId(userId);
            UserExtendDto userExtendDto = userExtendService.queryByUserId(userId);
            MailBean mailBean = new MailBean();
            mailBean.setSubject("封号提示");
            mailBean.setRecipient(userExtendDto.getEmail());
            mailBean.setContent(IS_LOGOUT);
            if (serviceId.equals("2")) { // msp服务销号 或者封号
                if (isLogout) {
                    userInfo.setStatus("2"); // 封号
                }else{
                    userInfo.setStatus("3"); // 销号
                }
                userInfoService.updateMsp(userInfo);
                userExtendService.sendMail(mailBean);
            }else { // 默认大屏服务销号 或者封号
                if (isLogout) {
                    userInfo.setStatus("2"); // 封号

                }else{
                    userInfo.setStatus("3"); // 销号
                }
                userInfoService.update(userInfo);
                userExtendService.sendMail(mailBean);
            }
            Set<String> strings = redisUtil.redisLike(userId);
            clearCache(strings, redisUtil); //清除缓存
            return Result.ok();
        }else {
            return Result.failure(USERNAME_Off_SITE,usernameOffSite);
        }
    }
    /**
     * 通过主键查询单条数据
     * 销号 或者封号
     * @return 单条数据
     */
    @GetMapping(value = "relieve",produces="application/json")
    @ApiOperation(value = "解除封号")
    @ResponseBody
    public Result relieve(@RequestHeader(value = "cloud-Auth-Token",required = false) String cloudAuthToken,
                                @RequestParam("serviceId") String serviceId,
                                @RequestParam("userId") String userId,
                                @RequestParam("isLogout") Boolean isLogout) throws Exception {
        if (redisUtil.exist(cloudAuthToken)) { // 销号 或者封号
            UserInfo userInfo = new UserInfo();
            userInfo.setId(userId);
            UserExtendDto userExtendDto = userExtendService.queryByUserId(userId);
            MailBean mailBean = new MailBean();
            mailBean.setSubject("账号解封提醒");
            mailBean.setRecipient(userExtendDto.getEmail());
            mailBean.setContent(SEND_RELIVE_INFO);
            if (serviceId.equals("2")) { // msp服务销号 或者封号
                if (isLogout) {
                    userInfo.setStatus("0"); // 封号
                }
                userInfoService.updateMsp(userInfo);
                userExtendService.sendMail(mailBean);
            }else { // 默认大屏服务销号 或者封号
                if (isLogout) {
                    userInfo.setStatus("0"); // 封号
                }
                userInfoService.update(userInfo);
                userExtendService.sendMail(mailBean);
            }
            Set<String> strings = redisUtil.redisLike(userId);
            clearCache(strings, redisUtil); //清除缓存
            return Result.ok();
        }else {
            return Result.failure(USERNAME_Off_SITE,usernameOffSite);
        }
    }
}
